package vip.zhenzicheng.concurrent_program.interview.alternate_output_letters;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhenzicheng
 * @date: 2022-06-03 13:27
 */
public class Solution_Lock_Condition {

  public static void main(String[] args) {
    char[] aI = "1234567".toCharArray();
    char[] aC = "ABCDEFG".toCharArray();

    Lock lock = new ReentrantLock();
    Condition conditionT1 = lock.newCondition();
    Condition conditionT2 = lock.newCondition();

    new Thread(() -> {
      lock.lock();
      try {
        for (char c : aI) {
          System.out.print(c);
          conditionT2.signal();
          conditionT1.await();
        }

        conditionT2.signal();
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
      }
    }, "t1").start();

    new Thread(() -> {
      lock.lock();
      try {
        for (char c : aC) {
          System.out.print(c);
          conditionT1.signal();
          conditionT2.await();
        }

        conditionT1.signal();
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
      }
    }, "t2").start();
  }
}
